import React, { Component } from 'react';
import css from './index.less';
import FilterSearch from '@/components/FilterSearch';
import TableList from '@/components/TableList';
import { Button, Divider, Input, Modal, message } from 'antd';
import { connect } from 'dva';
import EditModal from '@/components/EditModal';
import { Link } from 'react-router-dom';
import Status from '@/pages/components/Status';
import { getStatus } from '@/utils/business';
import AuthButton from '@/components/AuthButton';
const { TextArea } = Input;
class roleManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      comment: '',
      select: null,
      selectProject: [],
      isBatch: false,
    };
  }
  filters = [
    {
      key: 'status',
      type: 'select',
      label: '审批状态',
      options: [
        {
          label: '待审批',
          value: '1',
        },
        {
          label: '已审批',
          value: '1',
        },
      ],
    },
    {
      key: 'year',
      type: 'select',
      label: '申报年份',
      options: this.props.dict.searchYear,
    },
    ,
    {
      key: 'name',
      type: 'input',
      label: '项目名称',
    },
  ];

  columns = [
    {
      title: '项目ID',
      dataIndex: ['project', 'no'],
      width: 150,
      render: (text, data) => (
        <Button type="link" onClick={() => this.goDetail(data, true)}>
          {text}
        </Button>
      ),
    },

    { title: '项目名称', dataIndex: 'name' },
    { title: '申报日期', dataIndex: 'createTime', format: 'YYYY-MM-DD' },
    { title: '项目性质', dataIndex: 'buildType' },
    { title: '项目类型', dataIndex: ['serviceTypeData', 'display'] },
    { title: '行业领域', dataIndex: ['professionData', 'display'] },
    { title: '总投资（万元）', dataIndex: 'totalInvestment', width: 150 },
    { title: '拟开建年份', dataIndex: 'expectStartYear' },
    {
      title: '审批状态',
      dataIndex: ['approveResult', 'result'],
      render: (text, data) => <Status data={data} type={1} />,
    },
    {
      title: '操作',
      render: (text, data) => (
        <>
          {!getStatus(data, 1) ? (
            <Button
              className="e-button"
              type="primary"
              key={text}
              onClick={() => this.openModal(data, false)}
            >
              审批
            </Button>
          ) : (
            ''
          )}
        </>
      ),
    },
  ];
  goDetail = (data, readOnly) => {
    const url = `projectApprove/planProjectApprove/edit?id=${data.uuid ||
      ''}&readOnly=${readOnly || ''}&fromType=3&isApprove=${
      data.approveResult.result !== true && data.approveResult.result !== false
        ? true
        : ''
    }`;
    this.props.dispatch({
      type: '$router/forward',
      payload: {
        url,
      },
    });
  };
  /**
   * 打开审批弹窗
   */
  openModal = (data, isBatch) => {
    this.setState({
      visible: true,
      select: data,
      isBatch,
    });
  };
  handleResult = type => {
    const { comment, select, selectProject, isBatch } = this.state;
    if (!comment && !type) {
      message.error('拒绝时请输入审批意见');
      return;
    }
    const uuid = select.approveResult && select.approveResult.uuid;
    const uuidList = selectProject.length
      ? selectProject.map(item => item.approveResult.uuid)
      : [];
    this.props
      .dispatch({
        type: '$request/post',
        payload: {
          url: isBatch
            ? '/api/project/approve/v1/approveList'
            : '/api/project/approve/v1/approve',
          data: {
            projectType: 'PLAN',
            comment: comment,
            result: type,
            uuid,
            uuidList,
          },
        },
      })
      .then(res => {
        message.success('审批成功');
        this.table.fetch();
        this.setState({ visible: false, selectProject: [] });
      });
  };
  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        selectProject: selectedRows,
      });
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows,
      );
    },
    getCheckboxProps: record => ({
      disabled:
        record.approveResult.result === true ||
        record.approveResult.result === false, // Column configuration not to be checked
      name: record.name,
    }),
  };
  render() {
    const { visible, comment, selectProject } = this.state;
    return (
      <div>
        <FilterSearch
          filters={this.filters}
          onSearch={val => this.table.fetch(val)}
        >
          <AuthButton
            type="primary"
            onClick={() => this.openModal(selectProject, true)}
            disabled={!selectProject.length}
            role="examine_plan_project"
          >
            批量审批
          </AuthButton>
        </FilterSearch>
        <TableList
          post
          rowKey="id"
          onRef={c => {
            this.table = c;
          }}
          tableProps={{
            rowSelection: {
              type: 'checkbox',
              ...this.rowSelection,
            },
          }}
          columns={this.columns}
          source="/api/project/approve/v1/planReport/query"
        />
        <Modal
          title="审批意见"
          visible={visible}
          okText="通过"
          cancelText="拒绝"
          onCancel={() => this.setState({ visible: false })}
          footer={[
            <AuthButton
              key="back"
              onClick={() => this.handleResult(false)}
              role="examine_plan_project"
            >
              拒绝
            </AuthButton>,
            <AuthButton
              type="primary"
              onClick={() => this.handleResult(true)}
              role="examine_plan_project"
            >
              通过
            </AuthButton>,
          ]}
        >
          <TextArea
            placeholder="审批意见，拒绝时必填"
            value={comment}
            onChange={e => this.setState({ comment: e.target.value })}
          />
        </Modal>
      </div>
    );
  }
}

export default connect(state => state.base)(roleManage);
